package com.example.jwt.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 判断当前用户是否具有访问 该路径 的角色
 */
@Slf4j
@Component
public class JwtUrlAccessDecisionManager implements AccessDecisionManager {

    /**
     * @param authentication   当前用户凭证, JwtTokenFilter 中通过校验的用户保存在 SecurityContextHolder 中, 传到了这里
     * @param object           当前请求路径
     * @param configAttributes 当前请求路径需要的角色列表, 从 JwtFilterInvocationSecurityMetadataSource 返回
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        Iterator<ConfigAttribute> iterator = configAttributes.iterator();
        if (configAttributes.isEmpty()) {
            return;
        }

        // 当前用户的权限信息(我这个demo直接把角色作为权限)
        List<String> authenticationRoles = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());

        while (iterator.hasNext()) {
            ConfigAttribute ca = iterator.next();
            // 当前请求需要的角色
            String needRole = ca.getAttribute();
            if(authenticationRoles.contains(needRole)){
                return;
            }
        }

        if(authentication instanceof AnonymousAuthenticationToken){
            log.warn("匿名用户无权访问 {} , 请先登陆", object.toString());
            throw new AccessDeniedException("请先登陆");
        }
        throw new AccessDeniedException("权限不足!");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
